package com.yf.course.modules.course.utils;

import okhttp3.*;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DashScopeChat {
    private static final String API_KEY = "sk-5fb4c90206e84a7b9d88fc91e72fbe44";
    private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    public static String callDashScopeAPI(String userMessage) {
        // 创建 OkHttp 客户端并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(300, java.util.concurrent.TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(600, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时时间
                .writeTimeout(300, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时时间
                .build();

        // 创建请求体
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("model", "qwen-max");

        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", userMessage);

        // 创建 JsonArray 并添加消息
        JsonArray messagesArray = new JsonArray();
        messagesArray.add(message);

        // 将 JsonArray 添加到请求体
        requestBody.add("messages", messagesArray);

        // 创建请求
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, requestBody.toString());
        Request request = new Request.Builder()
                .url(BASE_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 解析响应
            Gson gson = new Gson();
            JsonObject responseJson = gson.fromJson(response.body().string(), JsonObject.class);
            JsonObject choices = responseJson.getAsJsonArray("choices").get(0).getAsJsonObject();
            JsonObject messageObj = choices.getAsJsonObject("message");
            return messageObj.get("content").getAsString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}